package cn.itsource.hrm.service.impl;

import cn.itsource.hrm.domain.Employee;
import cn.itsource.hrm.domain.Meal;
import cn.itsource.hrm.domain.Tenant;
import cn.itsource.hrm.dto.EnteringDto;
import cn.itsource.hrm.mapper.EmployeeMapper;
import cn.itsource.hrm.mapper.TenantMapper;
import cn.itsource.hrm.service.ITenantService;
import cn.itsource.hrm.utils.encrypt.MD5;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author luo
 * @since 2020-04-20
 */
@Service
public class TenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> implements ITenantService {

    @Autowired
    private EmployeeMapper employeeMapper ;

    @Override
    public void entering(EnteringDto dto) {
        //1.判断公司姓名是否为空，不是空才可以进行一下保存操作
        Tenant tenant = dto.getTenant();

        if(!StringUtils.hasLength(tenant.getCompanyName())){
            throw new RuntimeException("公司名称不能为空");
        }
        //2.保存机构，获取需要的数据再存入
        Tenant tenant1 = new Tenant();
        tenant1.setAddress(tenant.getAddress());
        tenant1.setCompanyName(tenant.getCompanyName());
        tenant1.setCompanyNum(tenant.getCompanyNum());
        tenant1.setLogo(tenant.getLogo());
        tenant1.setTenantType(tenant.getTenantType());
        Date date = new Date();
        tenant1.setRegisterTime(date);
        //这里使用的常量
        tenant1.setState(Tenant.STATE_NORMAL);  //机构可用
        //保存
        baseMapper.insert(tenant1);

        Employee employee = dto.getEmployee();
        System.out.println(employee.getEmail());
        //3.保存管理员账号
        Employee employee1 = new Employee();
        //加密
        String md5 = MD5.getMD5(employee.getPassword() + "ababab");
        employee1.setEmail(employee.getEmail());
        employee1.setPassword(md5);
        employee1.setTel(employee.getTel());
        employee1.setUsername(employee.getUsername());
        employee1.setState(Employee.STATE_NORMAL);
        employee1.setInputTime(date);
        employee1.setTenantId(tenant1.getId());
        //设置为管理人员
        employee1.setType(Employee.TYPE_ADMIN);
        employeeMapper.insert(employee1);
        //4.保存(套餐机构中间表) 通过看数据库可知传入mealid 机构id
        Long mealId = dto.getMealId();
        baseMapper.intermediateTable(mealId,tenant1.getId(), Meal.STATE_UN_PAY);

    }
}
